package com.nantai.jiafang.nantaijiafang.view;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Matrix;
import android.graphics.Paint;
import android.graphics.Path;
import android.graphics.Rect;
import android.graphics.drawable.BitmapDrawable;
import android.util.AttributeSet;
import android.view.View;

import com.nantai.jiafang.nantaijiafang.R;
import com.nantai.jiafang.nantaijiafang.activity.ReportActivity;
import com.nantai.jiafang.nantaijiafang.bean.ReportInfo;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by cool on 16/9/27.
 */

public class ReportView extends View {

    private List<ReportInfo> mData = new ArrayList<>();
    private float defaultWeiht = dip2px(getContext(), 8);
    private float reportwidth = dip2px(getContext(), 20);
    private float topWidth = dip2px(getContext(), 8);
    private float topH = dip2px(getContext(), 3f);
    private Paint reportPaint;
    private Paint namePaint;
    private Paint valuePaint;
    private Paint alPaint;
    private Paint linePaint;
    private float mWidth;
    private boolean isBig = false;


    public ReportView(Context context) {
        super(context);
        init();
    }

    public ReportView(Context context, AttributeSet attrs) {
        super(context, attrs);
        init();
    }

    public ReportView(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        init();
    }

    public void setBig(boolean big) {
        isBig = big;
        if(isBig){
            reportwidth = dip2px(getContext(), 30);
            valuePaint.setTextSize(sp2px(getContext(), 15f));
            namePaint.setTextSize(sp2px(getContext(), 12f));
            topWidth = dip2px(getContext(), 12);
        }else{
            reportwidth = dip2px(getContext(), 20);
            valuePaint.setTextSize(sp2px(getContext(), 8f));
            namePaint.setTextSize(sp2px(getContext(), 8f));
            topWidth = dip2px(getContext(), 8);
        }
        requestLayout();
        postInvalidate();
    }

    private void init() {
        reportPaint = new Paint();
        reportPaint.setColor(Color.parseColor("#89aff4"));
        reportPaint.setAntiAlias(true);
        reportPaint.setStyle(Paint.Style.FILL_AND_STROKE);

        namePaint = new Paint();
        namePaint.setColor(Color.BLACK);
        namePaint.setAntiAlias(true);
        namePaint.setStyle(Paint.Style.FILL_AND_STROKE);
        namePaint.setTextSize(sp2px(getContext(), 8f));
        namePaint.setTextAlign(Paint.Align.LEFT);

        valuePaint = new Paint();
        valuePaint.setColor(Color.BLACK);
        valuePaint.setAntiAlias(true);
        valuePaint.setStyle(Paint.Style.FILL_AND_STROKE);
        valuePaint.setTextAlign(Paint.Align.RIGHT);
        valuePaint.setTextSize(sp2px(getContext(), 8f));


        alPaint = new Paint();
        alPaint.setColor(Color.BLACK);
        alPaint.setAntiAlias(true);
        alPaint.setStrokeWidth(dip2px(getContext(), 3));

        linePaint = new Paint();
        linePaint.setColor(Color.BLACK);
        linePaint.setAntiAlias(true);
        linePaint.setStrokeWidth(dip2px(getContext(), 1.5f));



    }

    @Override
    protected void onDraw(Canvas canvas) {
        super.onDraw(canvas);

        if (mData.size() == 0) {
            return;
        }

        float per = dip2px(getContext(), 300) / 120f;

        mWidth = getWidth();

        BitmapDrawable drawable = (BitmapDrawable) getResources().getDrawable(R.mipmap.ic_launcher);



        drawAL(dip2px(getContext(), 0), (int) (dip2px(getContext(), 2) + topWidth), (int) mWidth - dip2px(getContext(), 0), (int) (dip2px(getContext(), 2) + topWidth), canvas, alPaint);
        canvas.drawLine(dip2px(getContext(), 0), (int) (dip2px(getContext(), 2) + topWidth), (int) mWidth - dip2px(getContext(), 3), (int) (dip2px(getContext(), 2) + topWidth),linePaint);

        drawAL(dip2px(getContext(),2), (int) (dip2px(getContext(), 2) + topWidth), dip2px(getContext(),2), (int) ((int) ((mData.size()) * (defaultWeiht + reportwidth) + topWidth + dip2px(getContext(), 8))), canvas, alPaint);
        canvas.drawLine(dip2px(getContext(),2), (int) (dip2px(getContext(), 2) + topWidth), dip2px(getContext(),2), (int) ((int) ((mData.size()) * (defaultWeiht + reportwidth) + topWidth + dip2px(getContext(), 5))),linePaint);

        canvas.drawText("0", dip2px(getContext(), 0) + topH, (int) (dip2px(getContext(), 0) + topWidth), namePaint);
        namePaint.setTextAlign(Paint.Align.CENTER);
        canvas.drawText("100%", (int) (100f * per) + topH, (int) (dip2px(getContext(), 0) + topWidth), namePaint);
        canvas.drawText("120%", dip2px(getContext(), 300) + topH, (int) (dip2px(getContext(), 0) + topWidth), namePaint);
        canvas.drawLine((int) (100f * per) + topH, (int) (dip2px(getContext(), 0) + topWidth), (int) (100f * per) + topH, (int) (dip2px(getContext(), 10) + topWidth), namePaint);

        namePaint.setTextAlign(Paint.Align.LEFT);
        for (int i = 0; i < mData.size(); i++) {
            canvas.drawRect(0 + topH, (i + 1) * defaultWeiht + i * reportwidth + topWidth, Float.parseFloat(mData.get(i).getUseRate()) * per + topH, (i + 1) * (defaultWeiht + reportwidth) + topWidth, reportPaint);

            Rect targetRect = new Rect((int) (0 + topH), (int) ((i + 1) * defaultWeiht + i * reportwidth + topWidth), (int) (Float.parseFloat(mData.get(i).getUseRate()) * per + topH), (int) ((i + 1) * (defaultWeiht + reportwidth) + topWidth));
            Paint.FontMetricsInt fontMetrics = namePaint.getFontMetricsInt();
            int baseline = (targetRect.bottom + targetRect.top - fontMetrics.bottom - fontMetrics.top) / 2;

            canvas.drawText(mData.get(i).getComponentInvInfo(), dip2px(getContext(), 2) + topH, baseline, namePaint);


            canvas.drawText(mData.get(i).getUseRate() + "%", mWidth - dip2px(getContext(), 0), baseline, valuePaint);
            if("DESC".equals(ReportActivity.order)&&i<=2) {
                canvas.drawBitmap(zoomImg(drawable.getBitmap(), dip2px(getContext(), 10), dip2px(getContext(), 10)), targetRect.right + dip2px(getContext(), 3), (float) ((i + 1) * (defaultWeiht + reportwidth) + topWidth-reportwidth*0.75) , null);
            }
        }


    }

    public static Bitmap zoomImg(Bitmap bm, int newWidth , int newHeight){
        // 获得图片的宽高
        int width = bm.getWidth();
        int height = bm.getHeight();
        // 计算缩放比例
        float scaleWidth = ((float) newWidth) / width;
        float scaleHeight = ((float) newHeight) / height;
        // 取得想要缩放的matrix参数
        Matrix matrix = new Matrix();
        matrix.postScale(scaleWidth, scaleHeight);
        // 得到新的图片   www.2cto.com
        Bitmap newbm = Bitmap.createBitmap(bm, 0, 0, width, height, matrix, true);
        return newbm;
    }

    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {

//        mViewHeight = measureHeight(heightMeasureSpec);
        if (mData.size() > 0) {
            setMeasuredDimension(widthMeasureSpec, (int) (mData.size() * (defaultWeiht + reportwidth) + dip2px(getContext(), 20)));
        }
        else {
            setMeasuredDimension(0,0);
        }
    }

    private int measureHeight(int measureSpec) {
        int preferred = 0;
        return getMeasurement(measureSpec, preferred);
    }

    private int getMeasurement(int measureSpec, int preferred) {
        int specSize = MeasureSpec.getSize(measureSpec);
        int measurement;
        switch (MeasureSpec.getMode(measureSpec)) {
            case MeasureSpec.EXACTLY:
                measurement = specSize;
                break;
            case MeasureSpec.AT_MOST:
                measurement = Math.min(preferred, specSize);
                break;
            default:
                measurement = preferred;
                break;
        }
        return measurement;
    }


    /**
     * 根据手机的分辨率从 dp 的单位 转成为 px(像素)
     */
    public static int dip2px(Context context, float dpValue) {
        final float scale = context.getResources().getDisplayMetrics().density;
        return (int) (dpValue * scale + 0.5f);
    }

    public void setmData(List<ReportInfo> list) {
        this.mData = list;
        requestLayout();
        invalidate();
    }


    /**
     * 根据手机的分辨率从 sp 的单位 转成为 px
     */
    public static float sp2px(Context context, float sp) {
        final float scale = context.getResources().getDisplayMetrics().scaledDensity;
        return sp * scale;
    }



    public void drawAL(int fx, int fy, int sx, int sy, Canvas myCanvas, Paint paint) {
        double H = 16;
        double L = 7;
        int x3 = 0;
        int y3 = 0;
        int x4 = 0;
        int y4 = 0;
        double awrad = Math.atan(L / H);
        double arraow_len = Math.sqrt(L * L + H * H);
        double[] arrXY_1 = rotateVec(sx - fx, sy - fy, awrad, true, arraow_len);
        double[] arrXY_2 = rotateVec(sx - fx, sy - fy, -awrad, true, arraow_len);
        double x_3 = sx - arrXY_1[0];
        double y_3 = sy - arrXY_1[1];
        double x_4 = sx - arrXY_2[0];
        double y_4 = sy - arrXY_2[1];
        Double X3 = new Double(x_3);
        x3 = X3.intValue();
        Double Y3 = new Double(y_3);
        y3 = Y3.intValue();
        Double X4 = new Double(x_4);
        x4 = X4.intValue();
        Double Y4 = new Double(y_4);
        y4 = Y4.intValue();
//        myCanvas.drawLine(fx, fy, (float) (sx - arraow_len + dip2px(getContext(), 1)), sy, paint);
        Path triangle = new Path();
        triangle.moveTo(sx, sy);
        triangle.lineTo(x3, y3);
        triangle.lineTo(x4, y4);
        triangle.close();
        myCanvas.drawPath(triangle, paint);

    }

    public double[] rotateVec(int px, int py, double ang, boolean isChLen, double newLen) {
        double mathstr[] = new double[2];
        double vx = px * Math.cos(ang) - py * Math.sin(ang);
        double vy = px * Math.sin(ang) + py * Math.cos(ang);
        if (isChLen) {
            double d = Math.sqrt(vx * vx + vy * vy);
            vx = vx / d * newLen;
            vy = vy / d * newLen;
            mathstr[0] = vx;
            mathstr[1] = vy;
        }
        return mathstr;
    }
}
